package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.domain.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findMemberByTel(telephone);
    }

    @Override
    public void add(Member member) {

        String password = member.getPassword();
        if (password != null) {
            //会员的密码需要通过MD5加密处理
            member.setPassword(MD5Utils.md5(password));
        }
        memberDao.add(member);
    }

    @Override
    public Map<String, Object> getMonthsAndMCount() {
        Map<String, Object> map = new HashMap<>();

        //数据库中原始数据
        List<String> allRegTime = memberDao.findAllRegTime();
        //利用set集合的特点去重
        Set<String> result1 = new TreeSet<>();
        result1.addAll(allRegTime);
        //获取不带日的时间
        List<String> result2 = new ArrayList<>();
        for (String s : result1) {
            String[] split = s.split("-");
            result2.add(split[0] + "-" + split[1]);
        }
        //利用set集合的特点去重,获取我想要的数据
        Set<String> result3 = new TreeSet<>();
        result3.addAll(result2);


        //利用sql获取该月注册的会员的数量
        List<Integer> memberCount = new ArrayList<>();
        for (String month : result3) {
            memberCount.add(memberDao.findMCountByMonth(month));
        }

        map.put("months", result3);
        map.put("memberCount", memberCount);

        return map;
    }

    @Override
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> list = new ArrayList<>();
        for (String month : months) {
            list.add(memberDao.findMemberCountBeforeDate(month));
        }
        return list;
    }


}
